package com.crossriver.crgis.portlet;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.UUID;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;
import javax.xml.rpc.ServiceException;

import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tempuri.TransactionQuery;
import org.tempuri.TransactionQueryLocator;
import org.tempuri.TransactionQuerySoap;

import com.crossriver.crgis.cofo.beans.ApplicationBean;
import com.crossriver.crgis.cofo.util.Emailer;
import com.crossriver.crgis.cofo.util.PaymentBean;
import com.crossriver.crgis.cofo.util.PaymentServiceUtil;
import com.crossriver.crgis.database.model.Application_C_of_O;
import com.crossriver.crgis.database.model.Bank_Payment_Slip;
import com.crossriver.crgis.database.model.Company_Contact_Person;
import com.crossriver.crgis.database.model.Contact_Information;
import com.crossriver.crgis.database.model.Held_Plots;
import com.crossriver.crgis.database.model.Individual_Information;
import com.crossriver.crgis.database.model.Transactions;
import com.crossriver.crgis.database.model.impl.Bank_Payment_SlipImpl;
import com.crossriver.crgis.database.service.Application_C_of_OLocalServiceUtil;
import com.crossriver.crgis.database.service.Bank_Payment_SlipLocalServiceUtil;
import com.crossriver.crgis.database.service.Company_Contact_PersonLocalServiceUtil;
import com.crossriver.crgis.database.service.Contact_InformationLocalServiceUtil;
import com.crossriver.crgis.database.service.Individual_InformationLocalServiceUtil;
import com.crossriver.crgis.database.service.TransactionsLocalServiceUtil;
import com.crossriver.crgis.mail.util.MailMessages;
import com.interswitchng.services.WebPayServiceStub;
import com.interswitchng.services.WebPayServiceStub.GetTransactionData;
import com.interswitchng.services.WebPayServiceStub.TransactionQueryResponse;
import com.interswitchng.services.WebPayService_PortType;
import com.interswitchng.services.WebPayService_Service;
import com.interswitchng.services.WebPayService_ServiceLocator;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.Base64;
import com.liferay.portal.kernel.util.CalendarFactoryUtil;
import com.liferay.portal.kernel.util.DateUtil;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.ListType;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.AuthTokenUtil;
import com.liferay.portal.service.ListTypeServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.PortalPreferences;
import com.liferay.portlet.PortletPreferencesFactoryUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.sun.tools.javac.util.Version;

/**
 * Portlet implementation class Payments
 */
public class Payments extends MVCPortlet {
	
	private static Log log = LogFactory.getLog(Payments.class);

	@Override
	public void serveResource(ResourceRequest request, ResourceResponse response)
			throws IOException, PortletException {
 
		String applicationId = request.getParameter("applicationId");
		
		String operationType = ParamUtil.getString(request, "operationType");
		
		if("LOGTRANS".equalsIgnoreCase(operationType)){
			System.out.println("log transaction and get out");
			

			//insert the record into the transaction history.
			String transNo = UUID.randomUUID().toString();		
			Transactions  trans = TransactionsLocalServiceUtil.createTransactions(transNo);

			ThemeDisplay themeDisplay = (ThemeDisplay) request
			.getAttribute(WebKeys.THEME_DISPLAY); 
			User user = themeDisplay.getUser();
			trans.setUserId(""+ user.getUserId());
			trans.setTransactionNo(transNo);//what is this going to be?
			
			PaymentBean payBean = (PaymentBean)request.getPortletSession().getAttribute("payBean");
				
			
			trans.setItemId(payBean.getPay_item_id());
			trans.setItemDescription(payBean.getPay_item_name());
			trans.setPaymentType("INTERSWITCH - WebPayDirect");

			trans.setPaymentDate(CalendarFactoryUtil.getCalendar().getTime());
			trans.setApplicationType(payBean.getPay_item_id());


			trans.setAmount(new Double(payBean.getTotalAmount().doubleValue()));
			trans.setTransactionFee(new Double(payBean.getTransactionFees().doubleValue()));

			trans.setTransactionRef(payBean.getTransactionRef());
			trans.setStatus("PENDING");

			try {
				TransactionsLocalServiceUtil.updateTransactions(trans, true);
				
				String url = payBean.getSite_redirect_url() +  "&transactionNo=" + trans.getTransactionNo();
				
				payBean.setSite_redirect_url(url);
				request.getPortletSession().setAttribute("payBean", payBean);
				
				JSONObject jsonOustanding = JSONFactoryUtil.createJSONObject();
				
				jsonOustanding.put("site_url", url);
				response.setContentType("text/html");
				
				response.getWriter().println(jsonOustanding.toString());
				
				System.out.println(url);
				
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				log.info("There is a problem saving the transaction information >>" + e.getMessage());
			}
			
			return;
		}
		
		
//		logTransB4Interswitch();
		logTransB4InterswitchAJAX(request, response);
			
		//retrieve the application to get the fees to be paid.;
		Application_C_of_O application = null;
		
		String feeToPay="";
		try {
			application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
			
			String appType = application.getApplication();
			String useType = application.getLandUseType();
			String queryString = "";
			System.out.println(appType);
			if ("certification".equalsIgnoreCase(appType)){
				queryString = "com.teqbridgeltd.liferay.model.map.Fees.Application Fees for C of O";
			}else if("Re-certification".equalsIgnoreCase(appType)){
				queryString = "com.teqbridgeltd.liferay.model.map.Fees.Application Fees for C of O Recertification";
			}else if("stateLand".equalsIgnoreCase(appType)){
				
				queryString = "com.teqbridgeltd.liferay.model.map.Fees.Application Fees for Government Land";
			}
			List<ListType> mappedSubFees = ListTypeServiceUtil.getListTypes(queryString );
			
			boolean notFound = true;
			
			for (int i = 0; i < mappedSubFees.size(); i++) {
				ListType mappedSubFee = mappedSubFees.get(i);
				String feesPart = mappedSubFee.getName();
				
				String mappedUseType ="";
				
				if("AGRICULTURAL AND MIXED USE".equalsIgnoreCase(useType)){
					mappedUseType="Agricultural";
				}else if("RESIDENTIAL".equalsIgnoreCase(useType)){
					mappedUseType="Residential";
				}else if("COMMERCIAL".equalsIgnoreCase(useType)){
					mappedUseType="Commercial/Industrial";
				}else if("INDUSTRIAL".equalsIgnoreCase(useType)){
					mappedUseType="Commercial/Industrial";
				}else if("PUBLIC INSTITUTION".equalsIgnoreCase(useType)){
					mappedUseType="Govertment";
				}else if("PUBLIC UTILITY".equalsIgnoreCase(useType)){
					mappedUseType="Govertment";
				}else {
					mappedUseType="Others";
				}
				
				if("stateLand".equalsIgnoreCase(appType)){
					StringTokenizer strTok =  new StringTokenizer(feesPart, "~");
					strTok.nextToken(); strTok.nextToken(); //pick the last one
					feeToPay = strTok.nextToken();
					
					break;
				}else{
					if (feesPart.indexOf(mappedUseType) > 1){
						//fee found, extract and break
						//Application Fees for C of O (Agricultural)~A_COA~5000
						StringTokenizer strTok =  new StringTokenizer(feesPart, "~");
						strTok.nextToken(); strTok.nextToken(); //pick the last one
						feeToPay = strTok.nextToken();
						
						break;
					}
					
				}
				
			}
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		JSONObject jsonOustanding = JSONFactoryUtil.createJSONObject();
		
		jsonOustanding.put("applicationId", applicationId);
		jsonOustanding.put("outstandingPayment", feeToPay);
		jsonOustanding.put("paymentAmount",  feeToPay);
		
		//JSONArray jsonFeedEntries  = JSONFactoryUtil.createJSONArray();
		
		response.setContentType("text/html");
		
		response.getWriter().println(jsonOustanding.toString());

	}
	
	//

	public void cancel(ActionRequest actionRequest,
			ActionResponse actionResponse) {
		
		String paymentMode = "";
		paymentMode = "/html/payments/view.jsp";
		
		actionRequest.getPortletSession().removeAttribute("payBean");
		
		actionRequest.setAttribute("jspPage", paymentMode);
		actionResponse.setRenderParameter("jspPage",paymentMode);
	}
	
	@Override
	public void doView(
			RenderRequest renderRequest, RenderResponse renderResponse)
		throws IOException, PortletException {
		
		if(log.isInfoEnabled()){
			log.info("in do view");
		}

		PaymentBean payBean  =  //new PaymentBean(); 
				(PaymentBean) renderRequest.getPortletSession().getAttribute("payBean");
		//42fc8e75-ea37-44f5-96f2-629cadf1a3e7
		//CRGIA-2012-012331-2012.10.24.10.57 network
		//CRGIA-2012-012331-2012.12.29.10.02 good
//		payBean.setTransactionRef("CRGIA-2012-012331-2012.10.24.10.57");
//		payBean.setProduct_id("3987");
//		payBean.setTotalAmount(new BigDecimal(10000.00));
//		payBean.setPaymentAmount(new BigDecimal(10000.00));
//		payBean.setTransactionFees(new BigDecimal(0.00));
		
		if(null != payBean){
			
			// this is coming from the menu
			HttpServletRequest request = PortalUtil
			.getHttpServletRequest(renderRequest);
			HttpServletRequest origRequest = PortalUtil
			.getOriginalServletRequest(request);
			String page = origRequest.getParameter("__page");

			if("home".equalsIgnoreCase(page)){
				//initialize
				renderRequest.getPortletSession().removeAttribute("payBean");
				
				//set to home page
				this.viewJSP = this.getInitParameter("view-jsp");
				super.doView(renderRequest, renderResponse);
			}else{
				//get the txn ref
				String txnref = payBean.getTransactionRef();
				System.out.println(txnref);
				log.info(txnref);
				
				//the trnsaction is added to the request scope
				queryTransaction(payBean, renderRequest, renderResponse);
			}
		}else{
			super.doView(renderRequest, renderResponse);
		}
		
	}
	
	


	
	public void queryTransaction(PaymentBean payBean, RenderRequest renderRequest, RenderResponse renderResponse){
		
		String productId = payBean.getProduct_id();
		String txnRef = payBean.getTransactionRef();
		
		
		WebPayService_Service service = new WebPayService_ServiceLocator();
		
		String wsURL = getInitParameter("interswitch_service_url");
		
		URL usrsvcurl = null;
		try {
			usrsvcurl = new URL(wsURL);
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String transactionNo = UUID.randomUUID().toString();	
		Transactions transactn = TransactionsLocalServiceUtil.createTransactions(transactionNo);
		transactn.setTransactionRef(payBean.getTransactionRef());
		
		try {
			
			String hash= "";
			String hash_key=this.getInitParameter("mac_key");
			
			String strToHash = productId + txnRef +hash_key ;
			
			System.out.println(strToHash);
			
			MessageDigest md = null;
			try {
				md = MessageDigest.getInstance("SHA-512");
				
				md.update(strToHash.getBytes());
				 
		        byte byteData[] = md.digest();
		 
		        //convert the byte to hex format method 1
		        StringBuffer sb = new StringBuffer();
		        for (int i = 0; i < byteData.length; i++) {
		         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
		        }
		        
		        hash = sb.toString().toUpperCase();
		        /////
		        //overwrite what is there now
		        /////
				//payBean.setHash(sb.toString().toUpperCase());
				
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				//payBean.setHash(strToHash);
			}
			
			TransactionQueryResponse transDataResp = PaymentServiceUtil.makeServiceCall(hash, productId, txnRef);
			
			//String returnMessage = 	transSoap.getTransactionAcquirerData(productId, txnRef);

			//System.out.println(tranData.get);
			
			String txnResp, txnDesc, last4DigitCard, merchantRef, payRef, retRef="";
			Long txnAmount= new Long(0);
			
			txnResp=txnDesc=last4DigitCard=merchantRef=payRef=retRef="";
			
			if(transactn != null){
				
				System.out.println(transDataResp.toString());
				
				if(transDataResp != null){
					txnResp=transDataResp.getResponseCode();
					
					if(transDataResp.getCardNumber() == null){
						System.out.println("Payment is cancelled");
						//TODO To ask if this is to be kept in the database for history of trials
						try {
							include("/html/payments/payment-mode.jsp", renderRequest, renderResponse);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (PortletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						return;
					}
					
					txnDesc=transDataResp.getResponseDescription();
					txnAmount=transDataResp.getAmount();
					last4DigitCard=transDataResp.getCardNumber();
					merchantRef=transDataResp.getMerchantReference();
					payRef=transDataResp.getPaymentReference(); 
					retRef= transDataResp.getRetrievalReferenceNumber();
				}
				
				transactn.setResponseCode(txnResp);
				transactn.setResponseDescription(txnDesc);
				transactn.setTransactionRef(payBean.getTransactionRef());
				
				
				
				if("00".equalsIgnoreCase(txnResp)){
					transactn.setStatus("COMPLETE");
				}else{
					transactn.setStatus("CANCELLED");
				}
				transactn.setPayRef(payRef);
				transactn.setCardNum(last4DigitCard);
				transactn.setRetRef(retRef)	;
				transactn.setApprovedAmount(new Double(txnAmount));
				transactn.setAmount(new Double(txnAmount));
				transactn.setPaymentType("INTERSWITCH - WebPayDirect");
				
				ThemeDisplay themeDisplay = 
				 (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY); 
				 
				transactn.setUserId(themeDisplay.getUserId() + "");
				transactn.setPaymentDate(CalendarFactoryUtil.getCalendar().getTime());
				
				transactn.setApplicationType(payBean.getPay_item_name().toUpperCase());
				
				TransactionsLocalServiceUtil.updateTransactions(transactn, true);
				
				renderRequest.setAttribute("trans", transactn);
				
				//send mail success or failure
				
				String applicationId = payBean.getApplicationId();
				//send success message
				if("00".equalsIgnoreCase(txnResp)){
					try {
						Application_C_of_O application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
						application.setStatus("PAYMENT_MADE");
						application = Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(application, true) ;
						
					
						String message = MailMessages.PAYMENT_CONFIRMATION;
						
						Contact_Information contact = Contact_InformationLocalServiceUtil.getContact_Information(applicationId);
						
						String appType = application.getApplicationType();
						String emailAddr = contact.getEmailAddress();
						
						if("Individual".equalsIgnoreCase(appType)){
							
							Individual_Information individual = Individual_InformationLocalServiceUtil.getIndividual_Information(applicationId);
							
							message = message.replaceAll("#CLIENT_NAME#", individual.getLastName() + " " + individual.getFirstName());
							message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());		
						}else{
							
							Company_Contact_Person coyContact = Company_Contact_PersonLocalServiceUtil.getCompany_Contact_Person(applicationId);
							
							message = message.replaceAll("#CLIENT_NAME#", coyContact.getLastName() + " " + coyContact.getFirstName());
							message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());
						}
						
						message = message.replaceAll("#REF_CODE#", transactn.getPayRef());
						message = message.replaceAll("#TRANS_REF_CODE#", transactn.getTransactionRef());
						message = message.replaceAll("#NAME_OF_TRANS#", transactn.getItemDescription());
						message = message.replaceAll("#TRANS_AMT#", transactn.getAmount().toString());
						message = message.replaceAll("#TRANS_ID#", transactn.getItemId());
						 
						//send mail to the CRGIS for notification of of completed application
						String from ="crgis@crossriverstate.gov.ng";
						String to = emailAddr;
						String bcc=null;
						String subject  =  application.getApplication().toUpperCase() + " - " + application.getReferenceNo() ;
						
						File[] attachments = null;
						
						try {
							Emailer.sendEmail(from, to, bcc, subject, message, attachments );
						} catch (Exception e) {
							SessionErrors.add(renderRequest, "problem-sending-mail");
							if(log.isInfoEnabled()){
								log.info(e.getMessage());
							}
							e.printStackTrace();
						}
					

						try {
							include("/html/payments/payment-success.jsp", renderRequest, renderResponse);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (PortletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						System.out.println("about making calls to get the transaction details");
						log.info("about making calls to get the transaction details");
						
						renderRequest.getPortletSession().removeAttribute("payBean");
						
					//SessionMessages.add(actionRequest, "webservice-call-for-query-successful-and-update-done");
					}catch(PortalException pe){
						pe.printStackTrace();
					}
				}else{
					//send failure message
					
					try {
						Application_C_of_O application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
//						application.setStatus("PAYMENT_MADE");
//						application = Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(application, true) ;
//											
						String message = MailMessages.INCOMPLETE_PAYMENT;
						
						Contact_Information contact = Contact_InformationLocalServiceUtil.getContact_Information(applicationId);
						
						String appType = application.getApplicationType();
						String emailAddr = contact.getEmailAddress();
						
						if("Individual".equalsIgnoreCase(appType)){
							
							Individual_Information individual = Individual_InformationLocalServiceUtil.getIndividual_Information(applicationId);
							
							message = message.replaceAll("#CLIENT_NAME#", individual.getLastName() + " " + individual.getFirstName());
							message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());		
						}else{
							
							Company_Contact_Person coyContact = Company_Contact_PersonLocalServiceUtil.getCompany_Contact_Person(applicationId);
							
							message = message.replaceAll("#CLIENT_NAME#", coyContact.getLastName() + " " + coyContact.getFirstName());
							message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());
						}
						
						message = message.replaceAll("#REF_CODE#", transactn.getPayRef());
						message = message.replaceAll("#TRANS_REF_CODE#", transactn.getTransactionRef());
						message = message.replaceAll("#NAME_OF_TRANS#", transactn.getItemDescription());
						message = message.replaceAll("#TRANS_AMT#", transactn.getAmount().toString());
						message = message.replaceAll("#TRANS_ID#", transactn.getItemId());
						message = message.replaceAll("#TRANS_RESP_DESC#", transactn.getResponseDescription());
						
						 
						//send mail to the CRGIS for notification of of completed application
						String from ="crgis@crossriverstate.gov.ng";
						String to = emailAddr;
						String bcc=null;
						String subject  =  application.getApplication().toUpperCase() + " - " + application.getReferenceNo() ;
						
						File[] attachments = null;
						
						try {
							Emailer.sendEmail(from, to, bcc, subject, message, attachments );
						} catch (Exception e) {
							SessionErrors.add(renderRequest, "problem-sending-mail");
							if(log.isInfoEnabled()){
								log.info(e.getMessage());
							}
							e.printStackTrace();
						}
					

						try {
							include("/html/payments/payment-failure.jsp", renderRequest, renderResponse);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (PortletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					//SessionMessages.add(actionRequest, "webservice-call-for-query-successful-and-update-done");
					}catch(PortalException pe){
						pe.printStackTrace();
					}
					
					
					System.out.println("send failure message");
				}
			
			}
			
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			SessionMessages.add(actionRequest, "webservice-call-for-query-failure-redo-for-complete-update");
		}

	}
	
	public void updateDepositSlip(ActionRequest actionRequest,
			ActionResponse actionResponse) {
		
		if (log.isInfoEnabled()) {
			log.info("In  updateDepositSlip ");
		}

		
		final UploadPortletRequest uploadRequest = PortalUtil
		.getUploadPortletRequest(actionRequest);

		//get the info and create the record.
		Bank_Payment_Slip bankSlp = new Bank_Payment_SlipImpl();
		PaymentBean payBean  = (PaymentBean) actionRequest.getPortletSession().getAttribute("payBean");
		//update payment info
		
		
		bankSlp.setApplicationId(payBean.getPayment_params());
		
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); 
		
		bankSlp.setUserId(themeDisplay.getUserId() + "");
		bankSlp.setRegistedDate(CalendarFactoryUtil.getCalendar().getTime());
		bankSlp.setStatus("NEW");
		
		bankSlp.setApprovedAmount(new Double(payBean.getOutstandingAmount().doubleValue()));
		
		bankSlp.setDepositorName(ParamUtil.getString(uploadRequest, "depositorName"));
		bankSlp.setDepSlipNo(ParamUtil.getString(uploadRequest, "depSlipNo"));
		bankSlp.setPaidAmount(ParamUtil.getDouble(uploadRequest, "paidAmount"));
		bankSlp.setBankName(ParamUtil.getString(uploadRequest, "bankName"));
		
		File uploadDepositSlip = uploadRequest.getFile("uploadDepositSlip");
		byte[] byteInFile = null;
		
		try {
			byteInFile = FileUtil.getBytes(uploadDepositSlip);
			if (byteInFile != null){
				bankSlp.setUploadDepositSlip(Base64.encode(byteInFile));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String uploadDepositSlipFilename = uploadRequest.getFileName("uploadDepositSlip");
		
		bankSlp.setUploadDepositSlipFilename(uploadDepositSlipFilename);
		
		boolean validationError = false;
		if(null == byteInFile || byteInFile.length == 0){
			SessionErrors.add(actionRequest, "payment-slip-file-must-be-uploaded");
			validationError = true;
		}
		
		String bankSlipUpload = bankSlp.getUploadDepositSlip();
		
		if(null == bankSlipUpload || bankSlipUpload.length() >= 540000){
			SessionErrors.add(actionRequest, "payment_slip_file_too_large", "payment_slip_file_too_large" );
			validationError = true;
		}
		
		
		if(null == bankSlp.getDepositorName() || "".equalsIgnoreCase(bankSlp.getDepositorName().trim())){
			SessionErrors.add(actionRequest, "depositors-name-must-not-be-blank");
			validationError = true;
		}
		
		if(null == bankSlp.getBankName() || "".equalsIgnoreCase(bankSlp.getBankName().trim())){
			SessionErrors.add(actionRequest, "bank-name-must-not-be-blank");
			validationError = true;
		}
		
		if(null == bankSlp.getPaidAmount() ){
			SessionErrors.add(actionRequest, "paid-amount-must-not-be-blank");
			validationError = true;
		}
		
		if(null == bankSlp.getDepSlipNo() || "".equalsIgnoreCase(bankSlp.getDepSlipNo().trim())){
			SessionErrors.add(actionRequest, "dep-slip-must-not-be-blank");
			validationError = true;
		}
		
		
		if(validationError){
			
			String paymentMode = "";
			paymentMode = "/html/payments/payment-mode-bank.jsp";
			
			actionRequest.setAttribute("bankSlp", bankSlp);
			actionRequest.setAttribute("payBean", payBean);
			
			
			actionRequest.setAttribute("jspPage", paymentMode);
			actionResponse.setRenderParameter("jspPage",paymentMode);
			
			return;
			
		}
		
		
		try {
			Bank_Payment_SlipLocalServiceUtil.updateBank_Payment_Slip(bankSlp, true);
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//update application with UPDATED_PAY_SLIP
		
		try {
			Application_C_of_O application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(bankSlp.getApplicationId());
			
			application.setStatus("UPDATED_PAY_SLIP");
			
			Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(application, true);
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//
		String paymentMode = "";
		paymentMode = "/html/payments/payment-mode-bank_update-success.jsp";
		
		
		actionRequest.setAttribute("payBean", payBean);
		
		actionRequest.setAttribute("jspPage", paymentMode);
		actionResponse.setRenderParameter("jspPage",paymentMode);
	}
	
	public void logTransB4Interswitch(ActionRequest actionRequest,
			ActionResponse actionResponse){
		
		String paymentMode = "/html/payments/payment-mode-interswitch.jsp";
		 
		PaymentBean payBean  = (PaymentBean) actionRequest.getPortletSession().getAttribute("payBean");
		actionRequest.setAttribute("payBean", payBean);
		
		actionRequest.getPortletSession().setAttribute("payBean", payBean);
		
		
		actionRequest.setAttribute("jspPage", paymentMode);
		actionResponse.setRenderParameter("jspPage",paymentMode);
		
	}
	
	private void logTransB4InterswitchAJAX( ResourceRequest request, ResourceResponse response){
		
		String paymentMode = "/html/payments/payment-mode-interswitch.jsp";
		 
		PaymentBean payBean  = (PaymentBean) request.getPortletSession().getAttribute("payBean");
		request.setAttribute("payBean", payBean);
		
		request.getPortletSession().setAttribute("payBean", payBean);
		
		request.setAttribute("jspPage", paymentMode);
		
	}
	
	public void proceedToPayment(ActionRequest actionRequest,
			ActionResponse actionResponse) {
		if (log.isInfoEnabled()) {
			log.info("In  proceedToPayment ");
		}
		
		PaymentBean payBean = new PaymentBean();
	
		//get the amount to be paid ans store in the portlet session
		String applicationId = ParamUtil.getString(actionRequest, "applicationId");
		BigDecimal outstandingPayment = new BigDecimal( ParamUtil.getFloat(actionRequest, "outstandingAmount"));
		
		BigDecimal paymentAmount = new BigDecimal(ParamUtil.getDouble(actionRequest, "paymentAmount"));
		
		
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest
		.getAttribute(WebKeys.THEME_DISPLAY); 
		
		User user = themeDisplay.getUser();
		
		payBean.setCurrency("566");
		payBean.setApplicationId(applicationId);
		//payBean.setPayment_params(applicationId);
		payBean.setOutstandingAmount(outstandingPayment);
		
		try {
			PortalPreferences pref = PortletPreferencesFactoryUtil.getPortalPreferences(actionRequest);
			System.out.println(pref);
		} catch (SystemException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String site_name = this.getInitParameter("site_name");
		
		payBean.setSite_name(site_name);
		payBean.setCust_id("" + user.getEmailAddress());
				
		
		HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest); 
		String token = AuthTokenUtil.getToken(request);


		String namespace = actionResponse.getNamespace();
		String strippedNSpace = namespace.substring(1, namespace.length()-1);
		

		String site_redirect_url= site_name + "/group/crgia/payments?p_auth=" + token +
				"&p_p_lifecycle=1" +
				"&p_p_state=normal&p_p_mode=view&p_p_col_id=column-2&p_p_col_count=1" +
				"&_" +
				strippedNSpace+ 
				"_javax.portlet.action=processDirectPayResponse" +
				"&p_p_id=" +
				strippedNSpace + "&echo=Payment" ;  
				
		payBean.setSite_redirect_url(site_redirect_url);
		
		payBean.setCust_id_desc("Email");
		payBean.setCust_name("" + user.getFullName().toUpperCase());
	
		Application_C_of_O application = null;
		
		try {
			application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String payItemId = application.getApplication().toUpperCase() +"-" + application.getApplicationType().toUpperCase();
		
		
		if(products.size() == 0){
			pupulateProducts();
		}
		
		
		payBean.setProduct_id(products.get(payItemId));
		//3987
		
		String product_id = this.getInitParameter("product_id");
		payBean.setProduct_id(product_id); //3987   //to externalize this
		payBean.setPay_item_id(application.getReferenceNo());
		
		//101
		String pay_tem_id = this.getInitParameter("pay_tem_id");
		payBean.setPay_item_id(pay_tem_id); //"101");  //to externalise this
		payBean.setPay_item_name(("Application Fees " +payItemId).toUpperCase() );
		
		
		String sNextCounter = "";
		try {
			sNextCounter = "000000"
				+ CounterLocalServiceUtil.increment();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String referenceNo = "PMT-"
			+ sNextCounter.substring(sNextCounter.length() - 6,
					sNextCounter.length());
		
		payBean.setTxn_no(referenceNo);
		
		Date cal = CalendarFactoryUtil.getCalendar().getTime();
		
		SimpleDateFormat sdfDate = new SimpleDateFormat("dd-MMM-yy hh:mm:ss");
		String localDateTime = sdfDate.format(cal);
		
		payBean.setLocal_date_time(localDateTime);
		payBean.setPaymentAmount(paymentAmount.setScale(2));
		
		//
		BigDecimal transactionFees = new BigDecimal(0);
		payBean.setTransactionFees(transactionFees.setScale(2));
		
		String transRef = application.getReferenceNo() + "-" 
			+ DateUtil.getCurrentDate("yyyy.mm.dd.MM.ss", null);
		payBean.setTransactionRef( transRef);
		
		payBean.setTotalAmount(paymentAmount.add(transactionFees).setScale(2));
		
		String s_totalAmount = payBean.getTotalAmount().toPlainString().replace(".", "");
		payBean.setS_totalAmount(s_totalAmount);
		
		String hash_key=this.getInitParameter("mac_key");
			//"F64AC041AE5041BDD2B1A88CF895C847825F183DF8D3E32D1C4C4C351C1A26FD5F22448FD59FE3B56F9138D1C050DBFCC58E714F39335E5AF9D8C06CA9B11B74";
		String strToHash = transRef + payBean.getProduct_id() + payBean.getPay_item_id() + 
			payBean.getS_totalAmount() + payBean.getSite_redirect_url() +hash_key ;
				
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA-512");
			
			md.update(strToHash.getBytes());
			 
	        byte byteData[] = md.digest();
	 
	        //convert the byte to hex format method 1
	        StringBuffer sb = new StringBuffer();
	        for (int i = 0; i < byteData.length; i++) {
	         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
	        }
	        
	        /////
	        //overwrite what is there now
	        /////
			payBean.setHash(sb.toString().toUpperCase());
			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			payBean.setHash(strToHash);
		}
		System.out.println(payBean.getHash());
		
		actionRequest.getPortletSession().setAttribute("payBean", payBean);
		
		String paymentMode = "/html/payments/payment-mode.jsp";
		actionRequest
				.setAttribute("jspPage", paymentMode);
		actionResponse.setRenderParameter("jspPage",
				paymentMode);

	}
	
	public void showApplications(ActionRequest actionRequest,
			ActionResponse actionResponse) {
		if (log.isInfoEnabled()) {
			log.info("In  showApplications ");
		}
		
		String paymentType = ParamUtil.getString(actionRequest, "paymentType");
		String application, applicationType ;
		application = applicationType ="";
		if("individual-certification".equalsIgnoreCase(paymentType)){
			application = "certification";
			applicationType = "individual";
		}else if("individual-re-certification".equalsIgnoreCase(paymentType)){
			application = "re-certification";
			applicationType = "individual";
		}else if("organisation-certification".equalsIgnoreCase(paymentType)){
			application = "certification";
			applicationType = "organisation";
		}else if("organisation-re-certification".equalsIgnoreCase(paymentType)){
			application = "re-certification";
			applicationType = "organisation";
		}else if("individual-stateland".equalsIgnoreCase(paymentType)){
			application = "stateLand";
			applicationType = "individual";			
		}else if("organisation-stateland".equalsIgnoreCase(paymentType)){
			application = "stateLand";
			applicationType = "organisation";			
		}
		
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest
		.getAttribute(WebKeys.THEME_DISPLAY); 
		String userId = ""+ themeDisplay.getUserId();
			
		
		List<Application_C_of_O> apps;
		try {
			apps = Application_C_of_OLocalServiceUtil.
				getApplication_C_of_OByUserId(userId);
		} catch (SystemException e) {
			if(log.isDebugEnabled()){
				log.debug("There is a problem retrieving applicatioons for user with ID>>>" + userId);
			}
			
			SessionErrors.add(actionRequest, "application-retrieval-error");
			
			return;
		}
		
		//lopp through the apps
		
		List<ApplicationBean> requestedApps = new ArrayList<ApplicationBean>(); 
		for (Iterator iterator = apps.iterator(); iterator.hasNext();) {
			Application_C_of_O application_C_of_O = (Application_C_of_O) iterator
					.next();
			
			ApplicationBean  requestedApp = new ApplicationBean();
			if(application.equalsIgnoreCase(application_C_of_O.getApplication()) &&
					(applicationType.equalsIgnoreCase(application_C_of_O.getApplicationType())) &&
							("submitted".equalsIgnoreCase(application_C_of_O.getStatus()))	){
				
				//retrieve the application to get the fees to be paid.;
				requestedApp.setApplication_id(application_C_of_O.getApplicationId());
				requestedApp.setApplication(application_C_of_O.getApplication());
				requestedApp.setStart_date(application_C_of_O.getApplicationStartDate());
				requestedApp.setReference_no(application_C_of_O.getReferenceNo());
				requestedApp.setStatus(application_C_of_O.getStatus());
				requestedApp.setSubmitted_date(application_C_of_O.getDateOfApplication());
				
				
				String feeToPay="";
				try {
					
					String appType = application_C_of_O.getApplication();
					String useType = application_C_of_O.getLandUseType();
					String queryString = "";
					System.out.println(appType);
					if ("certification".equalsIgnoreCase(appType)){
						queryString = "com.teqbridgeltd.liferay.model.map.Fees.Application Fees for C of O";
					}else if("Re-certification".equalsIgnoreCase(appType)){
						queryString = "com.teqbridgeltd.liferay.model.map.Fees.Application Fees for C of O Recertification";
					}else if("stateLand".equalsIgnoreCase(appType)){
						
						queryString = "com.teqbridgeltd.liferay.model.map.Fees.Application Fees for Government Land";
					}
					List<ListType> mappedSubFees = ListTypeServiceUtil.getListTypes(queryString );
					
					boolean notFound = true;
					
					for (int i = 0; i < mappedSubFees.size(); i++) {
						ListType mappedSubFee = mappedSubFees.get(i);
						String feesPart = mappedSubFee.getName();
						
						String mappedUseType ="";
						
						if("AGRICULTURAL AND MIXED USE".equalsIgnoreCase(useType)){
							mappedUseType="Agricultural";
						}else if("RESIDENTIAL".equalsIgnoreCase(useType)){
							mappedUseType="Residential";
						}else if("COMMERCIAL".equalsIgnoreCase(useType)){
							mappedUseType="Commercial/Industrial";
						}else if("INDUSTRIAL".equalsIgnoreCase(useType)){
							mappedUseType="Commercial/Industrial";
						}else if("PUBLIC INSTITUTION".equalsIgnoreCase(useType)){
							mappedUseType="Govertment";
						}else if("PUBLIC UTILITY".equalsIgnoreCase(useType)){
							mappedUseType="Govertment";
						}else {
							mappedUseType="Others";
						}
						
						if("stateLand".equalsIgnoreCase(appType)){
							StringTokenizer strTok =  new StringTokenizer(feesPart, "~");
							strTok.nextToken(); strTok.nextToken(); //pick the last one
							feeToPay = strTok.nextToken();
							
							break;
						}else{
							if (feesPart.indexOf(mappedUseType) > 1){
								//fee found, extract and break
								//Application Fees for C of O (Agricultural)~A_COA~5000
								StringTokenizer strTok =  new StringTokenizer(feesPart, "~");
								strTok.nextToken(); strTok.nextToken(); //pick the last one
								feeToPay = strTok.nextToken();
								
								break;
							}
							
						}
						
					}
				} catch (SystemException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				requestedApp.setFees(new Double(feeToPay));
				
				requestedApps.add(requestedApp);
			}
		}
		
		actionRequest.setAttribute("requestedApps", requestedApps);
		actionRequest.setAttribute("application", application);
		actionRequest.setAttribute("applicationType", applicationType);
		
		actionRequest.getPortletSession().setAttribute("application", application);
		actionRequest.getPortletSession().setAttribute("applicationType", applicationType);

		String view = "/html/payments/view.jsp";
		actionRequest
				.setAttribute("jspPage", view);
		actionResponse.setRenderParameter("jspPage",
				view);
	}

	
	public void pickPaymentMode(ActionRequest actionRequest,
			ActionResponse actionResponse) {
		
		if (log.isInfoEnabled()) {
			log.info("In  pickPaymentMode ");
		}
		
		String rd = ParamUtil.getString(actionRequest, "rd");
		
		//TODO
		//validate that some is picked.
		boolean validationError = false;
		if("".equalsIgnoreCase(rd)){
			SessionErrors.add(actionRequest, "pick-payment-mode");
			
			validationError = true;
			
		}
		
		if(validationError){
			
			
			String paymentMode = "/html/payments/payment-mode.jsp";
			
			PaymentBean payBean  = (PaymentBean) actionRequest.getPortletSession().getAttribute("payBean");
			actionRequest.setAttribute("payBean", payBean);
			
			//CRGIA-2012-012331-2012.43.29.10.20
			String transRef = payBean.getTransactionRef().substring(0, 17) + "-" 
			+ DateUtil.getCurrentDate("yyyy.mm.dd.MM.ss", null);
				payBean.setTransactionRef( transRef);
			
			payBean.setTransactionRef(transRef);
			
			String hash_key=this.getInitParameter("mac_key");
			String strToHash = transRef + payBean.getProduct_id() + payBean.getPay_item_id() + 
				payBean.getS_totalAmount() + payBean.getSite_redirect_url() +hash_key ;
					
			MessageDigest md = null;
			try {
				md = MessageDigest.getInstance("SHA-512");
				
				md.update(strToHash.getBytes());
				 
		        byte byteData[] = md.digest();
		 
		        //convert the byte to hex format method 1
		        StringBuffer sb = new StringBuffer();
		        for (int i = 0; i < byteData.length; i++) {
		         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
		        }
		        
		        /////
		        //overwrite what is there now
		        /////
				payBean.setHash(sb.toString().toUpperCase());
				
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				payBean.setHash(strToHash);
			}
			
			actionRequest.getPortletSession().setAttribute("payBean", payBean);
			
			
			actionRequest.setAttribute("jspPage", paymentMode);
			actionResponse.setRenderParameter("jspPage",paymentMode);
			
			return;
		}

		
		String paymentMode = "";

		if(rd.equalsIgnoreCase("Interswich")){
			paymentMode = "/html/payments/payment-mode-interswitch.jsp";
		}else{
			paymentMode = "/html/payments/payment-mode-bank.jsp";
		}
		
		PaymentBean payBean  = (PaymentBean) actionRequest.getPortletSession().getAttribute("payBean");
		actionRequest.setAttribute("payBean", payBean);
		
		actionRequest.getPortletSession().setAttribute("payBean", payBean);
		
		
		actionRequest.setAttribute("jspPage", paymentMode);
		actionResponse.setRenderParameter("jspPage",paymentMode);
		
	}
	
	
//	public void processDirectPayResponse(ActionRequest actionRequest,
//			ActionResponse actionResponse) {
//		
//		if (log.isInfoEnabled()) {
//			log.info("In  processDirectPayResponse ");
//		}
//
//
//		//get the response code
//		HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest); 
//		String token = AuthTokenUtil.getToken(request);
//
//		HttpServletRequest origRequest = PortalUtil.getOriginalServletRequest(request);
//		String responseCode = origRequest.getParameter("resp");
//		String responseDesc = origRequest.getParameter("desc");
//		String txnRef = origRequest.getParameter("txnref");
//		String payRef = origRequest.getParameter("payRef");
//		String retRef = origRequest.getParameter("retRef");
//		String cardNum = origRequest.getParameter("cardNum");
//		String transactionNo = origRequest.getParameter("transactionNo");
//		
//		
//		PaymentBean payBean = (PaymentBean)actionRequest.getPortletSession().getAttribute("payBean");
//		
//		Transactions trans = null;
//		try {
//			trans = TransactionsLocalServiceUtil.getTransactions(transactionNo);
//			
//			trans.setResponseCode(responseCode);
//			trans.setResponseDescription(responseDesc);
//			trans.setTransactionRef(txnRef); 
//			trans.setPayRef(payRef);
//			trans.setRetRef(retRef);
//			trans.setCardNum(cardNum);
//			trans.setStatus("COMPLETE");
//			
//			
//			TransactionsLocalServiceUtil.updateTransactions(trans, true);
//			
//		} catch (PortalException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		} catch (SystemException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//
//		
//		String paymentStatus = "/html/payments/payment-failure.jsp";
//
//		
//		
//		if("00".equalsIgnoreCase(responseCode)){
//			if(log.isInfoEnabled()){
//				log.info("Transaction " + txnRef + " was successful >>> " + responseDesc);
//			}
//			paymentStatus = "/html/payments/payment-success.jsp";
//			//display right page
//			
//			String applicationId = payBean.getPayment_params();
//			//send success message
//			try {
//				Application_C_of_O application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
//				application.setStatus("PAYMENT_MADE");
//				application = Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(application, true) ;
//				
//				actionRequest.setAttribute("trans", trans);
//				
//				String message = MailMessages.PAYMENT_CONFIRMATION;
//				
//				Contact_Information contact = Contact_InformationLocalServiceUtil.getContact_Information(applicationId);
//				
//				String appType = application.getApplicationType();
//				String emailAddr = contact.getEmailAddress();
//				
//				if("Individual".equalsIgnoreCase(appType)){
//					
//					Individual_Information individual = Individual_InformationLocalServiceUtil.getIndividual_Information(applicationId);
//					
//					message = message.replaceAll("#CLIENT_NAME#", individual.getLastName() + " " + individual.getFirstName());
//					message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());		
//				}else{
//					
//					Company_Contact_Person coyContact = Company_Contact_PersonLocalServiceUtil.getCompany_Contact_Person(applicationId);
//					
//					message = message.replaceAll("#CLIENT_NAME#", coyContact.getLastName() + " " + coyContact.getFirstName());
//					message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());
//				}
//				
//				message = message.replaceAll("#REF_CODE#", trans.getPayRef());
//				message = message.replaceAll("#TRANS_REF_CODE#", trans.getTransactionRef());
//				message = message.replaceAll("#NAME_OF_TRANS#", trans.getItemDescription());
//				message = message.replaceAll("#TRANS_AMT#", trans.getAmount().toString());
//				message = message.replaceAll("#TRANS_ID#", trans.getItemId());
//				 
//				//send mail to the CRGIS for notification of of completed application
//				String from ="crgis@crossriverstate.gov.ng";
//				String to = emailAddr;
//				String bcc=null;
//				String subject  =  application.getApplication().toUpperCase() + " - " + application.getReferenceNo() ;
//				
//				File[] attachments = null;
//				
//				try {
//					Emailer.sendEmail(from, to, bcc, subject, message, attachments );
//				} catch (Exception e) {
//					SessionErrors.add(actionRequest, "problem-sending-mail");
//					if(log.isInfoEnabled()){
//						log.info(e.getMessage());
//					}
//					e.printStackTrace();
//				}
//				
//				
//			}  catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			
//			//change the status of the application
//			//remove the item from the session
//			actionRequest.getPortletSession().removeAttribute("payBean");
//
//		}else{
//			
//			if(log.isInfoEnabled()){
//				log.info("Transaction " + txnRef + " failed >>> " + responseDesc);
//			}
//			
//			actionRequest.setAttribute("trans", trans);
//			
//			paymentStatus = "/html/payments/payment-failure.jsp";
//			
//			//send failure message
//			
//		}
//		actionRequest.setAttribute("jspPage", paymentStatus);
//		actionResponse.setRenderParameter("jspPage", paymentStatus);
//		
//		
//	}	
//	
	
	private static Map<String, String> products = new HashMap<String, String>();
	
	private static void pupulateProducts(){
		
		products.put("CERTIFICATION-INDIVIDUAL", "01");
		products.put("CERTIFICATION-ORGANISATION", "02");
		products.put("RE-CERTIFICATION-INDIVIDUAL", "03");
		products.put("RE-CERTIFICATION-ORGANISATION", "04");
		products.put("STATELAND-INDIVIDUAL", "05");
		products.put("STATELAND-ORGANISATION", "06");
		
	}

	
	/**
	 * This method is used to override the addSuccessMessage in the parent
	 * class. This override ensures that success message (that is displayed as
	 * default whenever any request is successfully submitted) is prevented.
	 * 
	 * We like to have control over this and this what this override ensures.
	 * 
	 */
	@Override
	protected void addSuccessMessage(ActionRequest actionRequest,
			ActionResponse actionResponse) {

		if (!addProcessActionSuccessMessage) {
			return;
		}
	}
	

	

	private static Map responseCode = new HashMap();
	
}


/*
	public void queryTransactionOLD(PaymentBean payBean, RenderRequest renderRequest, RenderResponse renderResponse){
		
		String productId = payBean.getProduct_id();
		String txnRef = payBean.getTransactionRef();
		
		
		TransactionQuery tran = new TransactionQueryLocator();
//		WebPayService_Service service = null;
		
		String wsURL = getInitParameter("interswitch_service_url");
		
		URL usrsvcurl = null;
		try {
			usrsvcurl = new URL(wsURL);
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String transactionNo = UUID.randomUUID().toString();	
		Transactions transactn = TransactionsLocalServiceUtil.createTransactions(transactionNo);
		transactn.setTransactionRef(payBean.getTransactionRef());
		
		try {
			TransactionQuerySoap transSoap = tran.getTransactionQuerySoap(usrsvcurl);
			
			
			String returnMessage = 	transSoap.getTransactionAcquirerData(productId, txnRef);

			System.out.println(returnMessage);
			
			
			
			String txnResp, txnDesc, txnAmount, last4DigitCard, merchantRef, payRef, retRef="";
			
			txnResp=txnDesc=txnAmount=last4DigitCard=merchantRef=payRef=retRef="";
			
			if(transactn != null){
				
				//successful - 00:Approved Successful:78500:5674:TIYOKFEL:GTB|WEB|UNN|19-01-2007|000009:000002349635
				//91:Bank or switch network error:1000000:3386:::::
				//	00:Approved Successful:1000000:3386:CRGIA-2012-012331-2012.10.24.10.57:ECO2|WEB|CRG|24-10-2012|016388:000000540977:FBN:First Bank of Nigeria Plc
				 
				 //failure - 14:Invalid Card Number:0:5674:TIYOKFEL:GTB|WEB|UNN|19-01-2007|: 
				 
				 
				 //Transaction Response : Transaction Description : Approved Amount (amount in small denomination): Last
				 //four digits of the card : Merchant Reference : Payment Reference : Bank Reference : Acquiring Bank Code :
				//	 Acquiring Bank Name

				
				StringTokenizer strTokMessage = new StringTokenizer(returnMessage, ":");
				txnResp=strTokMessage.nextToken();
				txnDesc=strTokMessage.nextToken();
				txnAmount=strTokMessage.nextToken();
				last4DigitCard=strTokMessage.nextToken();
				try{
					merchantRef=strTokMessage.nextToken();
					payRef=strTokMessage.nextToken();
				}catch(Exception ex){
					
				}
				
				
				if("00".equalsIgnoreCase(txnResp)){
					retRef=strTokMessage.nextToken();
				}
				
				transactn.setResponseCode(txnResp);
				transactn.setResponseDescription(txnDesc);
				transactn.setTransactionRef(payBean.getTransactionRef());
				if("00".equalsIgnoreCase(txnResp)){
					transactn.setStatus("COMPLETE");
				}else{
					transactn.setStatus("CANCELLED");
				}
				transactn.setPayRef(payRef);
				transactn.setCardNum(last4DigitCard);
				transactn.setRetRef(retRef)	;
				transactn.setApprovedAmount(new Double(txnAmount));
				transactn.setAmount(new Double(txnAmount));
				transactn.setPaymentType("INTERSWITCH - WebPayDirect");
				
				ThemeDisplay themeDisplay = 
				 (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY); 
				 
				transactn.setUserId(themeDisplay.getUserId() + "");
				transactn.setPaymentDate(CalendarFactoryUtil.getCalendar().getTime());
				
				
				TransactionsLocalServiceUtil.updateTransactions(transactn, true);
				
				renderRequest.setAttribute("trans", transactn);
				
				//send mail success or failure
				
				String applicationId = payBean.getApplicationId();
				//send success message
				if("00".equalsIgnoreCase(txnResp)){
					try {
						Application_C_of_O application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
						application.setStatus("PAYMENT_MADE");
						application = Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(application, true) ;
						
					
						String message = MailMessages.PAYMENT_CONFIRMATION;
						
						Contact_Information contact = Contact_InformationLocalServiceUtil.getContact_Information(applicationId);
						
						String appType = application.getApplicationType();
						String emailAddr = contact.getEmailAddress();
						
						if("Individual".equalsIgnoreCase(appType)){
							
							Individual_Information individual = Individual_InformationLocalServiceUtil.getIndividual_Information(applicationId);
							
							message = message.replaceAll("#CLIENT_NAME#", individual.getLastName() + " " + individual.getFirstName());
							message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());		
						}else{
							
							Company_Contact_Person coyContact = Company_Contact_PersonLocalServiceUtil.getCompany_Contact_Person(applicationId);
							
							message = message.replaceAll("#CLIENT_NAME#", coyContact.getLastName() + " " + coyContact.getFirstName());
							message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());
						}
						
						message = message.replaceAll("#REF_CODE#", transactn.getPayRef());
						message = message.replaceAll("#TRANS_REF_CODE#", transactn.getTransactionRef());
						message = message.replaceAll("#NAME_OF_TRANS#", transactn.getItemDescription());
						message = message.replaceAll("#TRANS_AMT#", transactn.getAmount().toString());
						message = message.replaceAll("#TRANS_ID#", transactn.getItemId());
						 
						//send mail to the CRGIS for notification of of completed application
						String from ="crgis@crossriverstate.gov.ng";
						String to = emailAddr;
						String bcc=null;
						String subject  =  application.getApplication().toUpperCase() + " - " + application.getReferenceNo() ;
						
						File[] attachments = null;
						
						try {
							Emailer.sendEmail(from, to, bcc, subject, message, attachments );
						} catch (Exception e) {
							SessionErrors.add(renderRequest, "problem-sending-mail");
							if(log.isInfoEnabled()){
								log.info(e.getMessage());
							}
							e.printStackTrace();
						}
					

						try {
							include("/html/payments/payment-success.jsp", renderRequest, renderResponse);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (PortletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					//SessionMessages.add(actionRequest, "webservice-call-for-query-successful-and-update-done");
					}catch(PortalException pe){
						pe.printStackTrace();
					}
				}else{
					//send failure message
					
					try {
						Application_C_of_O application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
//						application.setStatus("PAYMENT_MADE");
//						application = Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(application, true) ;
//											
						String message = MailMessages.INCOMPLETE_PAYMENT;
						
						Contact_Information contact = Contact_InformationLocalServiceUtil.getContact_Information(applicationId);
						
						String appType = application.getApplicationType();
						String emailAddr = contact.getEmailAddress();
						
						if("Individual".equalsIgnoreCase(appType)){
							
							Individual_Information individual = Individual_InformationLocalServiceUtil.getIndividual_Information(applicationId);
							
							message = message.replaceAll("#CLIENT_NAME#", individual.getLastName() + " " + individual.getFirstName());
							message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());		
						}else{
							
							Company_Contact_Person coyContact = Company_Contact_PersonLocalServiceUtil.getCompany_Contact_Person(applicationId);
							
							message = message.replaceAll("#CLIENT_NAME#", coyContact.getLastName() + " " + coyContact.getFirstName());
							message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());
						}
						
						message = message.replaceAll("#REF_CODE#", transactn.getPayRef());
						message = message.replaceAll("#TRANS_REF_CODE#", transactn.getTransactionRef());
						message = message.replaceAll("#NAME_OF_TRANS#", transactn.getItemDescription());
						message = message.replaceAll("#TRANS_AMT#", transactn.getAmount().toString());
						message = message.replaceAll("#TRANS_ID#", transactn.getItemId());
						message = message.replaceAll("#TRANS_RESP_DESC#", transactn.getResponseDescription());
						
						 
						//send mail to the CRGIS for notification of of completed application
						String from ="crgis@crossriverstate.gov.ng";
						String to = emailAddr;
						String bcc=null;
						String subject  =  application.getApplication().toUpperCase() + " - " + application.getReferenceNo() ;
						
						File[] attachments = null;
						
						try {
							Emailer.sendEmail(from, to, bcc, subject, message, attachments );
						} catch (Exception e) {
							SessionErrors.add(renderRequest, "problem-sending-mail");
							if(log.isInfoEnabled()){
								log.info(e.getMessage());
							}
							e.printStackTrace();
						}
					

						try {
							include("/html/payments/payment-failure.jsp", renderRequest, renderResponse);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (PortletException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					//SessionMessages.add(actionRequest, "webservice-call-for-query-successful-and-update-done");
					}catch(PortalException pe){
						pe.printStackTrace();
					}
					
					
					System.out.println("send failure message");
				}
			
			}
			
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			SessionMessages.add(actionRequest, "webservice-call-for-query-failure-redo-for-complete-update");
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("webservice-call-for-query-failure-redo-for-complete-update");
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			SessionMessages.add(actionRequest, "webservice-call-for-query-failure-redo-for-complete-update");
		}

	}
	
*/
